package cn.rokhdelar.ams.management.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.rokhdelar.ams.management.domain.po.LoginUser;
import cn.rokhdelar.ams.management.domain.po.SysUser;
import cn.rokhdelar.ams.management.mapper.SysUserMapper;
import cn.rokhdelar.ams.management.service.LoginUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author rokhdelar
 * @since 2024-10-05
 */
@Service
@RequiredArgsConstructor
public class LoginUserServiceImpl implements LoginUserService {
    private final SysUserMapper sysUserMapper;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
        if (sysUser == null) {
            throw new UsernameNotFoundException(username);
        }
        Collection<String> authorities = sysUserMapper.selectUserAuthoritiesById(sysUser.getId());
        HashSet<GrantedAuthority> authorityHashSet = new HashSet<>();
        for (String authority : authorities) {
            if (StrUtil.isNotBlank(authority)) {
                authorityHashSet.add(new SimpleGrantedAuthority(authority));
            }
        }
        return new LoginUser(sysUser, authorityHashSet);
    }
}
